package org.example.reactive.demo1.api;

import lombok.RequiredArgsConstructor;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gong.Yang
 * 文件上传示例
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
public class FileApi {
    @PostMapping("/uploadFilePart")
    public Mono<String> uploadFilePart(@RequestPart Flux<FilePart> filePartFlux) {
        return filePartFlux.flatMap(filePart -> filePart
                        .transferTo(new File("E:/http/" + filePart.filename()))
                )
                //确保所有都上传完毕
                .then(Mono.just("success upload"));
    }

    @PostMapping("/uploadWebExchange")
    public Mono<String> uploadWebExchange(ServerWebExchange serverWebExchange) {
        return serverWebExchange.getMultipartData()
                .flatMap(formData -> {
                    List<Part> filePartFlux = formData.get("filePartFlux");
                    List<Mono<Void>> transferMons = new ArrayList<>();

                    for (Part filePartMono : filePartFlux) {
                        if (filePartMono instanceof FilePart filePart) {
                            Mono<Void> transferMono = filePart.transferTo(new File("E:/http/" + filePart.filename()));
                            transferMons.add(transferMono);
                        }
                    }

                    //等待所有上传完毕
                    return Flux.concat(transferMons).then(Mono.just("success upload"));
                });
    }
}
